import { getLocalHistories } from '@/utils/storage';
import { uniq } from 'lodash';

// 创建reducer文件，设置初始值, 合并reducer
const initialState = {
  // 断言类型
  suggests: [] as string[],
  histories: getLocalHistories(),
  // 改造results为对象，存储分页数据
  resultData: {
    per_page: 10,
    page: 1,
    total_count: 0,
    results: [] as ResultType[],
  },
};

export type ResultType = {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: {
    type: number;
    images: string[];
  };
  like_count: number;
  collect_count: number;
};

// 创建actionTYpe
type ActionType =
  | { type: 'search/saveSuggests'; payload: string[] }
  | { type: 'search/saveHistories'; payload: string }
  | { type: 'search/clearHistories' }
  | { type: 'search/saveResults'; payload: typeof initialState.resultData }
  | { type: 'search/updateResults'; payload: typeof initialState.resultData };

export default function searchReducer(
  state = initialState,
  action: ActionType // 不解构action
): typeof initialState {
  // 返回值加上类型
  // 编写保存的switch逻辑
  switch (action.type) {
    case 'search/saveSuggests':
      return {
        ...state,
        // 脏数据会返回null
        suggests: action.payload.filter((item) => !!item),
      };
    case 'search/saveHistories':
      return {
        ...state,
        // histories: [...(new Set([...state.histories, action.payload]) as any)],
        // 数组去重  lodash
        histories: uniq([action.payload, ...state.histories]).slice(0, 10),
      };
    case 'search/clearHistories':
      return {
        ...state,
        histories: [],
      };
    case 'search/saveResults':
      return {
        ...state,
        // 修改reducer计算过程
        resultData: {
          per_page: action.payload.per_page,
          page: action.payload.page,
          // 直接覆盖旧的数据
          results: [...(action.payload.results || [])],
          total_count: action.payload.total_count,
        },
      };
    case 'search/updateResults':
      return {
        ...state,
        resultData: {
          per_page: action.payload.per_page,
          page: action.payload.page,
          // 合并新的数据到数组中
          results: [...state.resultData.results, ...action.payload.results],
          total_count: action.payload.total_count,
        },
      };
    default:
      return state;
  }
}
